#region Namespaces

using System.IO;

using Vibstudio.X4NET.Text.Encoding.Core;

#endregion

namespace Vibstudio.X4NET.Text.Encoding
{
    /// <summary>
    /// Default implementation of charset detection interface. 
    /// The detector can be feed by a System.IO.Stream:
    /// <example>
    /// <code>
    /// using (FileStream fs = File.OpenRead(filename))
    /// {
    ///    CharsetDetector cdet = new CharsetDetector();
    ///    cdet.Feed(fs);
    ///    cdet.DataEnd();
    ///    Console.WriteLine("{0}, {1}", cdet.Charset, cdet.Confidence);
    /// }
    /// </code>
    /// </example>
    /// 
    ///  or by a byte array:
    /// 
    /// <example>
    /// <code>
    /// byte[] buff = new byte[1024];
    /// int read;
    /// while ((read = stream.Read(buff, 0, buff.Length)) > 0 && !done)
    ///     Feed(buff, 0, read);
    /// cdet.DataEnd();
    /// Console.WriteLine("{0}, {1}", cdet.Charset, cdet.Confidence);
    /// </code>
    /// </example> 
    /// </summary>                
    public class CharsetDetector : UniversalDetector, ICharsetDetector
    {
        public CharsetDetector() : base(FILTER_ALL)
        {
        }

        public void Feed(byte[] buffer)
        {
            using (Stream stream = new MemoryStream(buffer))
            {
                Feed(stream);
            }
        }

        public void Feed(Stream stream)
        { 
            byte[] buff = new byte[1024];
            int read;
            while ((read = stream.Read(buff, 0, buff.Length)) > 0 && !done)
            {
                Feed(buff, 0, read);
            }
        }
        
        public bool IsDone() 
        {
            return done;
        }
        
        public override void Reset()
        {
            Charset = null;
            Confidence = 0.0f;
            base.Reset();
        }
        
        public string Charset { get; private set; }

        public float Confidence { get; private set; }

        protected override void Report(string charset, float confidence)
        {
            Charset = charset;
            Confidence = confidence;
        }
    }
}

